<template>
  <div class="sort-list-container">
    <GoodsItem v-for="good in goodList" :key="good.id" :goods="good" />
  </div>
  <XtxInfiniteLoad
    @load="loadNextPage"
    :isLoading="isLoading"
    :isFinished="isFinished"
  />
</template>

<script>
import { findSubCategoryGoods } from '@/api/category'
import { useRoute } from 'vue-router'
import { onMounted, ref, watch, inject } from 'vue'
import GoodsItem from '@/views/category/components/goods-item/index.vue'
export default {
  components: { GoodsItem },
  setup () {
    // 获取查询数据
    const filterData = inject('filterData')
    // 获取list
    const route = useRoute()
    const goodList = ref([])
    let reqParams = {
      page: 1,
      pageSize: 20,
      categoryId: route.params.id,
      sortField: null, // 排序类别
      attrs: [], // 商品属性
      brandId: null // 品牌名称
    }
    async function loadData () {
      const res = await findSubCategoryGoods(reqParams)
      goodList.value = res.result.items
    }
    onMounted(() => {
      loadData()
    })

    watch(
      () => { return filterData },
      () => {
        reqParams = { ...reqParams, ...filterData }
        loadData()
      },
      { deep: true }
    )

    //
    const isLoading = ref(false)
    const isFinished = ref(false)
    async function loadNextPage () {
      console.log('加载下一页')
      // 开始加载
      isLoading.value = true
      // 页数加一
      reqParams.page++
      // 发送请求
      const res = await findSubCategoryGoods(reqParams)
      goodList.value = [...goodList.value, ...res.result.items]
      isLoading.value = false
      if (res.result.items.length === 0) {
        isFinished.value = true
      }
    }
    return {
      goodList,
      loadNextPage,
      isLoading,
      isFinished
    }
  }
}
</script>

<style lang="scss" scoped>
.sort-list-container {
  display: flex;
  flex-wrap: wrap;
}
</style>
